package com.witframework.web.mvc;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.witframework.core.WitFrameWork;
import com.witframework.core.logic.ISimpleBaseService;
import com.witframework.util.BeanUtils;
import com.witframework.util.StringTools;

/**
 * 缺省实现的控制器，在请求的控制器未定义时，请求分发器会调用该控制器
 * @author wuxinyang
 * May 12, 2009 2:20:50 PM
 *
 */
public class BaseController implements Controller{
	
	public String getEntityClassName(WebContext webContext){
		return webContext.getParameter("entity");
	}
	public String getIndexPage(WebContext webContext){
		return webContext.getParameter("index");
	}
	public String getUpdatePage(WebContext webContext){
		return webContext.getParameter("update");
	}
	public String executor(WebContext webContext) {
		String entityName=entityName(webContext);
		if(entityName!=null){
			ISimpleBaseService service=(ISimpleBaseService)WitFrameWork.getSimpleBaseService(getEntityClassName(webContext));
			List<?> entityList = service.pagedQuery(webContext.getFilter(),webContext.getPageSortModel(entityName));
			webContext.setAttribute(entityName+"List",entityList);
			return getIndexPage(webContext);
		}
		return null;
	}
	/**
	 * 缺省的
	 * @param webContext
	 * @return 目标地址
	 */
	public String edit(WebContext webContext){
		String entityName=entityName(webContext);
		String[] ids=webContext.getSelItemList();
		if(ids.length>0){
			ISimpleBaseService service=(ISimpleBaseService)WitFrameWork.getSimpleBaseService(getEntityClassName(webContext));
			Object entity=service.get(ids[0]);
			webContext.setAttribute(entityName, entity);
		}
		return getUpdatePage(webContext);
	}
	/**
	 * 缺省的
	 * @param webContext
	 * @return 目标地址
	 */
	@Transactional
	public String store(WebContext webContext) {		
		ISimpleBaseService service=(ISimpleBaseService)WitFrameWork.getSimpleBaseService(getEntityClassName(webContext));
		Object entity=BeanUtils.newInstance(getEntityClassName(webContext));
		webContext.bindObject(entity);
		service.saveOrUpdate(entity);
		webContext.setPageInfo("操作成功");
		return "redirect://this";

	}
	/**
	 * 缺省的
	 * @param webContext
	 * @return 目标地址
	 */
	@Transactional
	public String delete(WebContext webContext){
		ISimpleBaseService service=(ISimpleBaseService)WitFrameWork.getSimpleBaseService(getEntityClassName(webContext));
		service.deleteAllByIds(webContext.getSelItemList());
		webContext.setPageInfo("操作成功");
		return "redirect://this";
	}
	
	private String entityName(WebContext webContext){
		String entityClassName=getEntityClassName(webContext);
		if(entityClassName!=null){
			return StringTools.lowerCaseFirstAlpha(BeanUtils.classForName(entityClassName).getSimpleName());
		}
		return null;
	}
}
